﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
public class MapColliderDataEditor
{
    [MenuItem("GameMapMaker/生成地图物理数据")]
    public static void ExportMapColliderData()
    {
        Hashtable curMapDic = GetCurMapTableDic();
        if (curMapDic == null)
        {
            Debug.LogError("场景名需要和地图表匹配(Maps.clj)");
            return;
        }
        GameObject MapG = GameObject.Find("map");
        if (MapG == null)
        {
            Debug.LogError("没有GameObject名为map的节点");
        }

        Collider[] collders =  MapG.GetComponentsInChildren<Collider>();
        object[] ExportData = new object[collders.Length];
        int CurI = 0;
        for (int i=0;i<collders.Length;i++)
        {
           Collider collider = collders[i];
            if (collider is BoxCollider)
            {
                object[] ValueDic = new object[5];
                ValueDic[0] = "BoxCollider";
                ExportData[CurI] = ValueDic;
                Vector4 PosV4 = GetBoxColliderBounds((BoxCollider)collider);
                ValueDic[1] = PosV4.x;
                ValueDic[2] = PosV4.y;
                ValueDic[3] = PosV4.z;
                ValueDic[4] = PosV4.w;
                CurI++;
            }
            if (collider is SphereCollider)
            {
                object[] ValueDic = new object[1];
                ValueDic[0] = "SphereCollider";
                ExportData[CurI] = ValueDic; ;
                CurI++;
            }

            if (collider is CapsuleCollider)
            {
                object[] ValueDic = new object[1];
                ValueDic[0] = "CapsuleCollider";
                ExportData[CurI] = ValueDic; ;
                CurI++;
            }
        }

        string MapDataStr = SGLisp.Helper.DataToLispString(ExportData);
        File.WriteAllText(Game.ConfigPath()+"/Map/"+ (string)curMapDic[":map-path"], MapDataStr);
        Debug.Log("生成成功");
    }

    static Vector4 GetBoxColliderBounds(BoxCollider boxCollider)
    {
        Vector4 vec4 = new Vector4();
        vec4.x = boxCollider.bounds.min.x;
        vec4.y = boxCollider.bounds.min.y;
        vec4.z = boxCollider.bounds.max.x;
        vec4.w = boxCollider.bounds.max.y;
        return vec4;
    }

    static Hashtable GetCurMapTableDic()
    {
        MapTableMgr.LoadFromFile(Game.ConfigPath() + "/Map", SGLisp.RT.MainContext);
        foreach (DictionaryEntry entry in MapTableMgr.MapIndexTable)
        {
            Hashtable ValueDic = (Hashtable)entry.Value;
            string mapName = (string)ValueDic[":map-name"];
            if (mapName == SGTools.GetCurSceneName())
            {
                return ValueDic;
            }
        }
        return null;
    }
}
